package ink.xiaobaibai.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.bo.AddUserDistributor;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.entity.AdminUser;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.units.MySecurity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @description: 用户测试类
 * @author: 小白白
 * @create: 2021-05-11
 **/

@RestController
@RequestMapping("/agent")
@Slf4j
@Api(tags = "部门经理接口")
@CrossOrigin
public class AgentController {

    @Autowired
    private IAdminUserService adminUserService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 部门经理为当前部门添加用户
     */
    @ApiOperation("部门经理为当前部门添加用户")
    @PostMapping("/add")
    @ResourcesRoleMapping(resourceName = "添加部门成员", includeRoleNames = {MyRole.AGENT})
    public ResponseFormat addUserToDep(@RequestBody @Validated AddUserDistributor addUserDistributor) {

        String userNumber = MySecurity.getUserNumber();

        if (this.validRepeatUserNumber(addUserDistributor.getUserNumber())) {
            return ResponseFormat.fail("账号重复");
        }

        if (this.validRepeatPhone(addUserDistributor.getPhone())) {
            return ResponseFormat.fail("手机重复");
        }

        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.select("department_id");
        q1.eq("user_number", userNumber);
        Integer departmentId = this.adminUserService.getOne(q1).getDepartmentId();

        AdminUser adminUser = new AdminUser(
                addUserDistributor.getUserName(), addUserDistributor.getUserNumber(), departmentId, addUserDistributor.getPhone(),
                this.passwordEncoder.encode(addUserDistributor.getPassword())
        );
        this.adminUserService.save(adminUser);
        return ResponseFormat.success();
    }


//    /**
//     * 部门经理为当前部门删除用户,不可删除
//     */
//    @ApiOperation("部门经理为当前部门添加用户")
//    @DeleteMapping("/delete")
//    @ResourcesRoleMapping(resourceName = "部门经理删除员工",includeRoleNames = MyRole.AGENT)
//    public ResponseFormat deleteUserById(@RequestParam("userId")Integer userId,Authentication authentication) {
//        String userNumber = authentication.getCredentials().toString();
//        if(!this.validDepartment(userNumber,userId)){
//            return ResponseFormat.fail("仅能操作本部门员工");
//        }
//        adminUserService.removeById(userId);
//        return ResponseFormat.ok("删除成功");
//    }

    private boolean validRepeatUserNumber(String userNumber) {
        //如果查到有两个账号
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.eq("user_number", userNumber);
        int count = this.adminUserService.count(q1);
        return count >= 1;
    }

    private boolean validRepeatPhone(String phone) {
        //如果查到有两个账号
        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.eq("user_phone", phone);
        int count = this.adminUserService.count(q1);
        return count >= 1;
    }

    /**
     * 操作对象是否本部门员工 true是本部门
     *
     * @param userNumber
     * @param userId
     * @return
     */
    private boolean validDepartment(String userNumber, Integer userId) {
        QueryWrapper<AdminUser> q0 = new QueryWrapper<>();
        q0.select("department_id");
        q0.eq("user_number", userNumber);
        Integer departmentId = this.adminUserService.getOne(q0).getDepartmentId();

        QueryWrapper<AdminUser> q1 = new QueryWrapper<>();
        q1.select("department_id");
        q1.eq("id", userId);
        AdminUser adminUser = this.adminUserService.getOne(q1);
        if (adminUser == null || !adminUser.getDepartmentId().equals(departmentId)) {
            return false;
        }
        return true;
    }

}
